import logging

from app.models.article import Article
from app.models.article import Category
"""
获取文章列表
"""
def get_article_list_by_author(author_id):
    """
    根据作者id获取文章列表
    """
    try:
        articles = Article.query.filter_by(author_id=author_id).all()
        article_list = []
        for article in articles:
            article_dict = article.to_dict()
            category = Category.query.get(article.category_id)
            if category:
                article_dict['category_name'] = category.name
            article_list.append(article_dict)
        return article_list
    except Exception as e:
        logging.error(f"获取文章列表失败:{str(e)}")
        return []

"""
新增文章
"""
def create_article_by_author(data):
    try:
        category = Category.query.get(data['category_id'])
        if not category:
            logging.error(f"分类ID不存在:{data['category_id']}")
            return None
            
        article = Article(
            author_id=data['author_id'],
            title=data['title'],
            content=data['content'],
            category_id=data['category_id']
        )
        article.save()
        return article.to_dict()
    except Exception as e:
        logging.error(f"新增文章失败:{str(e)}")
        return None

"""
修改文章
"""
def update_article_by_id(data):
    try:
        article = Article.query.get(data['id'])
        if article:
            article.title = data['title']
            article.content = data['content']
            article.category_id = data['category_id']
            article.save()
            return article.to_dict()
        else:
            return None
    except Exception as e:
        logging.error(f"修改文章失败:{str(e)}")
        return None

"""
删除文章
"""
def delete_article_by_id(article_id):
    try:
        article = Article.query.get(article_id)
        if article:
            article.delete()
            return True
        else:
            return False
    except Exception as e:
        logging.error(f"删除文章失败:{str(e)}")
        return False
